package aerolineasYVuelos

import org.hibernate.SessionFactory
import org.hibernate.cfg.AnnotationConfiguration
import org.hibernate.classic.Session
import org.hibernate.Transaction

object SessionManager {
  var sessionFactory: SessionFactory = _
  var tlSession: ThreadLocal[Session] = new ThreadLocal

  def getSessionFactory = {
    this.synchronized {
      org.apache.log4j.BasicConfigurator.configure();
      if (sessionFactory == null) {
        val cfg = new AnnotationConfiguration
        cfg.configure
        sessionFactory = cfg.buildSessionFactory
      }
    }
    sessionFactory
  }

  def runInSession[A](function: () => A): A = {
    val sessionFactory = SessionManager.getSessionFactory
    var transaction: Transaction = null
    var result: A = null.asInstanceOf[A]
    var session: Session = null

    try {
      var sessionAbierta = getSession != null
      if (!sessionAbierta) {
        session = sessionFactory.openSession
		tlSession.set(session)
        transaction = session.beginTransaction
      }

      result = function()

      if(!sessionAbierta){
    	  session.flush
    	  transaction.commit
      }
    } catch {
      case e: Exception => {
        if (transaction != null) {
          transaction.rollback
        }
        throw new RuntimeException(e)
      }
    } finally {
      if (session != null) {
        session.close
      }
      tlSession.set(null)
    }

    result
  }

  def getSession: Session = {
    tlSession.get
  }
  
  def deleteSessionFactory {
    	getSessionFactory.close()
    	sessionFactory = null
  }

}
